#include <stdio.h>
#include <sys/socket.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <ctype.h>
#include "server.h"
#include "workthread.h"
#include "hashtable.h"
#include "list.h"
#include "functions.h"



pthread_t * workthread_pid;

void init(int threadcount){
	initfuntable();
	g_requestlist=list_create();

	//create pthread
	workthread_pid=malloc(sizeof(pthread_t) * threadcount);

	int i;
	for(i=0;i<threadcount;i++){
		pthread_create((workthread_pid+i), NULL, workthread, NULL);
	}

}

inline char * strlwr(   char*   str   )
{
	char * orig=str;
	for(;*str!='\0';str++)
	  *str=tolower(*str);
	return orig;
}

void * workthread(void *arg){
	request_t req;
	for(;;){
		raw_request_t *pRawRequest=list_pop_head(g_requestlist);

		if(pRawRequest!=NULL){
			memset(&req,0,sizeof(req));
			getparam(req.cmd,sizeof(req.cmd),0,0,pRawRequest->buffer);
			getparam(req.content,sizeof(req.content),1,1,pRawRequest->buffer);
			req.fd=pRawRequest->fd;
			//dealRequest
			do_request(&req);
			free(pRawRequest);
		}else{
			usleep(20);
		}
	}
}

//0x804c648

void do_request(request_t* pRequest) {

	func fun=getfunction(strlwr(pRequest->cmd));
	if(fun){
		fun(pRequest);
	}else{
		do_something(pRequest);
	}
}



//
void trim(char * str){
	int n=strlen(str);
	int i=0,j=0;
	int start=0;
	while(i<n){
		if(!start){
			if(*(str+i)==0x20){
				i++;
			}else{
				start=1;
			}
		}else{
			char t=*(str+i);
			*(str+j)=t;
			i++;
			j++;
		}
	}
	
	i=j;
	while(j<n){
		*(str+j)=0;
		j++;
	}
	n=i;
	start=0;
	j=n-1;
	while(j>=0){
		if(*(str+j)==0x20){
			*(str+j)=0;
			j--;
		}else{
			break;
		}
	}
}
